package com.bq.gametrade.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.adapter.RechargeMoneyListAdapter;
import com.bq.gametrade.alipay.AliPayOrderInfoUtils;
import com.bq.gametrade.alipay.PayResult;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.AliPay;
import com.bq.gametrade.bean.RechargeMoney;
import com.bq.gametrade.bean.RechargeMoneyDetails;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.bean.WeChatPay;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.CustomerServiceDialog;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.switfpass.pay.MainApplication;
import com.switfpass.pay.activity.PayPlugin;
import com.switfpass.pay.bean.RequestMsg;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能：充值
 * <p>
 * Created by feel on 2016/12/5.
 */

public class RechargeActivity extends BaseActivity implements View.OnClickListener {


    private ImageView back,userService;
    private TextView tvTitle;
    private ImageView ivWeChatPay, ivAlipay;
    private RecyclerView recyclerView;
    private ArrayList<RechargeMoneyDetails> mList = new ArrayList<>();
    private RechargeMoneyListAdapter adapter;

    private String payMoneyId = "";
    private static String rechargeMoney = "";
    private UserInfoDetails userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        initView();
        getRechargeMoneyInfo();

    }

    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        showCustomerService(R.id.iv_userService);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("充值");
        ivWeChatPay = serchViewById(R.id.iv_weChatPay);
        ivWeChatPay.setOnClickListener(this);
        ivAlipay = serchViewById(R.id.iv_aliPay);
        ivAlipay.setOnClickListener(this);
        recyclerView = serchViewById(R.id.recylerview);
        adapter = new RechargeMoneyListAdapter(RechargeActivity.this, mList);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(new RechargeMoneyListAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(int position, String rechargeMoneyId) {
                payMoneyId = rechargeMoneyId;
                rechargeMoney = mList.get(position).money;
            }
        });

    }


    private void getRechargeMoneyInfo() {
        showSpotsDialog();
        VRHttp.getRechargeMoneyList(RechargeActivity.this, HttpLink.GET_RECHARGELIST_URL, null, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    RechargeMoney rechargeMoney = (RechargeMoney) response;
                    if(rechargeMoney.status.equals("0")){
                        mList = rechargeMoney.pay_list;
                        adapter.setData(mList);
                        adapter.notifyDataSetChanged();
                    }else if(rechargeMoney.status.equals("99")){
                        application.setUserInfo(null);
                        startActivity(new Intent(RechargeActivity.this,LoginActivity.class));
                        finish();
                    }else {
                        toastShow("获取充值金额失败，请重试");
                    }
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                closeSpotsDialog();
                toastShow("获取数据失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.iv_weChatPay:
                if (payMoneyId.equals("")) {
                    toastShow("充值金额还没有选择");
                    return;
                }
                weChatPay(rechargeMoney);
                break;
            case R.id.iv_aliPay:
                if (payMoneyId.equals("")) {
                    toastShow("充值金额还没有选择");
                    return;
                }
                toastShow("支付宝支付");
                aliPay(rechargeMoney);
                break;

        }
    }

    /****
     *微信支付类型：3
     *支付宝类型：1
     */

    /***
     * 微信支付
     */
    private void weChatPay(String myMoney) {

        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("account", userInfo.account);
        params.put("pay_money", myMoney);
        params.put("ticket", "0");
        params.put("channel_num", "0");
        params.put("payType", "3");
        VRHttp.sendWeChatPay(RechargeActivity.this, HttpLink.GET_ORDER_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    WeChatPay weChatPay = (WeChatPay) response;
                    if (weChatPay.status.equals("0")) {
                        SharedPreferencesUtils.saveValue(RechargeActivity.this, SharedPreferencesUtils.pay_order, weChatPay.gameOrderId);
                        RequestMsg msg = new RequestMsg();
                        msg.setTokenId(weChatPay.token_id);
                        msg.setTradeType(MainApplication.WX_APP_TYPE);
                        msg.setAppId(weChatPay.appid);
                        PayPlugin.unifiedAppPay(RechargeActivity.this, msg);
                    }else if(weChatPay.status.equals("99")){
                        toastShow("登录超时请重新操作");
                        application.setUserInfo(null);
                        startActivity(new Intent(RechargeActivity.this,LoginActivity.class));
                        finish();
                    }else if (weChatPay.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(RechargeActivity.this, LoginActivity.class));
                        finish();
                    }else{
                        toastShow("获取充值订单失败！请重试");
                    }
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });

    }


    /***
     * 支付宝支付
     */
    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == SDK_PAY_FLAG) {
                String resultStatus = new PayResult((String) msg.obj).getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if ("9000".equals(resultStatus)) {
                    queryOrder();
                    //后续业务处理
                } else if ("8000".equals(resultStatus)) { //"8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                    toastShow("支付结果确认中");
                } else { //其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                    toastShow("支付失败");
                }
            }
        }

        ;
    };

    private void aliPay(final String money) {

        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("account", userInfo.account);
        params.put("pay_money", rechargeMoney);
        params.put("ticket", "0");
        params.put("channel_num", "0");
        params.put("payType", "1");

        VRHttp.sendAliPay(RechargeActivity.this, HttpLink.GET_ORDER_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    AliPay aliPay = (AliPay) response;
                    if (aliPay.status.equals("0")) {
                        testAlipay(aliPay, money);
                    }else if(aliPay.status.equals("99")){
                        toastShow("登录超时请重新操作");
                        application.setUserInfo(null);
                        startActivity(new Intent(RechargeActivity.this,LoginActivity.class));
                        finish();
                    }else if (aliPay.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(RechargeActivity.this, LoginActivity.class));
                        finish();
                    }else{
                        toastShow("获取充值订单失败！请重试");
                    }
                }
            }
        });
    }


    public void testAlipay(final AliPay aliPay, String money) {
        if (TextUtils.isEmpty(aliPay.partner) || TextUtils.isEmpty(aliPay.rsa_private) || TextUtils.isEmpty(aliPay.alipay_account)) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        String orderInfo = AliPayOrderInfoUtils.getOrderInfo(aliPay, "比奇交易", "比奇平台充值", money);

/**
 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
 */
        String sign = AliPayOrderInfoUtils.sign(orderInfo, aliPay.rsa_private);
        try {
            /**
             * 仅需对sign 做URL编码
             */
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

/**
 * 完整的符合支付宝参数规范的订单信息
 */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + AliPayOrderInfoUtils.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RechargeActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
                SharedPreferencesUtils.saveValue(RechargeActivity.this, SharedPreferencesUtils.pay_order, aliPay.gameOrderId);
            }
        };

// 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    int count;

    private void queryOrder() {
        showSpotsDialog();
        String orderId = "";
        if (!SharedPreferencesUtils.getValue(RechargeActivity.this, SharedPreferencesUtils.pay_order, "").equals("")) {
            orderId = (String) SharedPreferencesUtils.getValue(RechargeActivity.this, SharedPreferencesUtils.pay_order, "");
        }
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("orderId", orderId);

        VRHttp.sendRequest(RechargeActivity.this, HttpLink.PAYORDER_QUERY, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    closeSpotsDialog();
                    ResponseBean responseBean = (ResponseBean) response;
                    if (responseBean.status.equals("0")) {
                        toastShow("恭喜你！充值成功");
                    }else {
                        count++;
                        if(count<3){
                            queryOrder();
                        }else {
                            toastShow("充值失败请联系客服");
                            CustomerServiceDialog dialog = new CustomerServiceDialog();
                            dialog.show(getSupportFragmentManager(),"");
                        }
                    }
                }


            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }

}
